$(function () {
  let form = layui.form;
  initArt();
  function initArt() {
    //获取数据
    $.ajax({
      type: "get",
      url: "/my/article/cates",
      // data: "data",
      // dataType: "dataType",
      success: function (res) {
        //链接模板
        let artHtml = template("art", res);
        // console.log(res);
        //渲染模板
        $("tbody").html(artHtml);
      },
    });
  }

  let index = null;
  /* --------点击添加弹窗事件--------- */
  $("#tjlb").on("click", function () {
    index = layui.layer.open({
      type: 1,
      closeBtn: 0,
      area: ["500px", "300px"],
      title: "添加类别",
      content: $("#tcadd").html(),
    });
  });
  /* --------添加功能--------- */
  $("body").on("submit", "#bdadd", function (e) {
    e.preventDefault();
    //获取 表单信息
    let data = $(this).serialize();
    $.ajax({
      type: "post",
      url: "/my/article/addcates",
      data,
      // dataType: "dataType",
      success: function (res) {
        if (res.status != 0) return layui.layer.msg(res.message);
        layui.layer.msg(res.message);
        layui.layer.close(index);
        initArt();
      },
    });
  });

  /* --------删除功能--------- */
  $("body").on("click", ".shan", function () {
    //获取id
    let id = $(this).attr("data-id");
    //是否确定删除提示框
    layer.confirm("确定删除?", { icon: 3, title: "提示" }, function (index) {
      //发送到服务器
      $.ajax({
        type: "get",
        url: `/my/article/deletecate/${id}`,
        success: function (res) {
          //展示删除结果
          if (res.status != 0) return layui.layer.msg(res.message);
          layui.layer.msg(res.message);
          initArt();
        },
      });
    });
  });

  /* --------编辑功能--------- */
  let indexgai = null;
  //点击编辑按键有弹窗
  $("body").on("click", "#gai", function () {
    // console.log(1);
    indexgai = layui.layer.open({
      type: 1,
      closeBtn: 0,
      area: ["500px", "300px"],
      title: "编辑内容",
      content: $("#tcbj").html(),
    });
    let id = $(this).attr("data-id");
    $.ajax({
      type: "get",
      url: `/my/article/cates/${id}`,
      // data: "data",
      // dataType: "dataType",
      success: function (res) {
        console.log(res);
        form.val("formTest", res.data);
      },
    });
  });
  //编辑功能
  $("body").on("submit", "#bdbj", function (e) {
    e.preventDefault();
    //获取表单里面的数据
    let data = form.val("formTest");
    console.log(data);
    //发送到服务器
    $.ajax({
      type: "post",
      url: "/my/article/updatecate",
      data,
      // dataType: "dataType",
      success: function (res) {
        if (res.status != 0) return layui.layer.msg(res.message);
        layui.layer.msg(res.message);
        layui.layer.close(indexgai);
        initArt();
      },
    });
  });

  //弹窗关闭  改
  $("body").on("click", ".guanbi", function () {
    layui.layer.close(indexgai);
    layui.layer.close(index);
  });
});
